#!/bin/bash
# 本工具用于对测试套的管理

g_topdir="$(realpath "$(dirname "$0")")"

# 新建测试套
# $1 -- 测试套名称
new_suite(){
    local suite_name="$1"
    if [ -z "$suite_name" ]; then
        echo "the suite name not set"
        return 1
    fi
    if [ -e ./$suite_name ]; then
        echo "the suite name $suite_name existed"
        return 1
    fi
    if ! echo $suite_name | grep -q "^[-_.a-zA-Z0-9]\+$"; then
        echo "the suite name can only [-_.a-zA-Z0-9]"
        return 1
    fi

    echo try git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name
    if ! git clone https://gitee.com/opencloudos-stream/test-suite-example.git ./$suite_name; then
        echo "clone the test-suite-example fail"
        rm -rf ./$suite_name
        return 1
    fi
    mv ./$suite_name/.gitignore ./$suite_name/gitignore
    rm -rf ./$suite_name/.git* ./$suite_name/tst_common
    mv ./$suite_name/gitignore ./$suite_name/.gitignore

    echo try git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common
    if ! git submodule add https://gitee.com/opencloudos-stream/test-suite-base.git ./$suite_name/tst_common; then
        echo "set the suite $suite_name submodule fail"
        rm -rf ./$suite_name
        return 1
    fi
    rm -f ./$suite_name/testcase/test_*

    return 0
}

# 编译测试套
# $* -- 要编译的测试套
compile_suite(){
    local tst_cwd="$(pwd)"
    local tst_ret=0
    local suite_list="$*"

    if [ -z "$suite_list" ]; then
        echo "suite not set, compile all"
        for f in */tsuite; do
            suite_list="$suite_list $(dirname $f)"
        done
    fi

    for suite in $suite_list; do
        cd "$tst_cwd" || return 1
        if [ ! -f ./$suite/tsuite ]; then
            echo "the suite $suite has no tsuite, ignore"
            continue
        fi
        cd ./$suite || return 1
        if ./tsuite compile; then
            echo "compile $suite success"
        else
            echo "compile $suite fail"
            tst_ret=1
        fi
    done

    cd "$tst_cwd" || return 1
    return $tst_ret
}

usage(){
    echo ""
    echo "Usage: $0 command"
    echo "command:"
    echo "    new suite_name: 新建测试套"
    echo "        suite_name: 【必选】新测试套名称"
    echo "    compile [suite_name...]: 编译测试套"
    echo "        suite_name: 【可选】要编译的测试套名称，不指定则编译所有测试套"
    echo ""
}

main(){
    local ret=0

    echo "g_topdir=$g_topdir"
    echo "change the CWD to $g_topdir"
    cd "$g_topdir"

    case "$1" in
        new)
            shift
            new_suite "$@" || ret=1
            ;;
        compile)
            shift
            compile_suite "$@" || ret=1
            ;;
        *)
            echo "unknow command: $*"
            usage
            return 1
            ;;
    esac

    return $ret
}

main "$@"
